# -*- coding: utf-8 -*-
##import simplejson as json
##import urllib2
##import urllib
##import twitter as pt
##from oauth import oauth
##from oauthtwitter import OAuthApi
##print 'Hello! This is my first-test application. Twit2VK coming soon!'
##print 'kol_progman'
consumer_key = "0lHX0Bo8wAmQH0Gcn3oBmA"
consumer_secret = "C3GSqzgQBOcIdSQyphT0tpYQ2PMRUPx939F4K39g"
oauth_token = "39931428-TD1H1rbiSB4QcKYlkFwXZNSOU7WLpCgxPJKkYMo"
oauth_token_secret = "xk8rHf5nEcjO7CBNsB1jjTSLMLAhmSLNSsNSN45F0"
FACEBOOK_APP_ID = "172289712800878"
FACEBOOK_APP_SECRET = "37d3138e345d99378e0964f687b1045b"
VKONTAKTE_APP_ID = "2026533"
VKONTAKTE_APP_SECRET = "9lKZmS0cNc6ZUg3kZThT"
##
###api = OAuthApi(consumer_key, consumer_secret, oauth_token, oauth_token_secret)
####api = pt.Api(consumer_key, consumer_secret, oauth_token, oauth_token_secret)
####api.PostUpdate('')
####api = pt.Api(consumer_key=consumer_key,consumer_secret=consumer_secret, access_token_key=oauth_token, access_token_secret=oauth_token_secret)
###print [s.user.name for s in statuses]
##host = 'http://vkontakte.ru/login.php'
##post = urllib.urlencode({'app' : '2013450',
##                         'layout' : 'touch',
##                         'type' : 'browser',
##                         'settings' : str(4096+8192)})
##
##url = 'http://vkontakte.ru/login.php?type=browser&app=2013450&layout=touch&settings=12288'
##session =''
import logging
import os
import facebook

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template


class UserVK(db.Model):
    id = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    name = db.StringProperty(required=True)
    sid = db.StringProperty(required=True)
    secret = db.StringProperty(required=True)
    expire = db.IntegerProperty(default = 0,required=True)


class UserFB(db.Model):
    id = db.StringProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)
    name = db.StringProperty(required=True)
    profile_url = db.StringProperty(required=True)
    access_token = db.StringProperty(required=True)


class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <body>
              <form action="signVK" method="get">
                <div><input type="submit" value="sign VK"></div>
              </form>
              <form action="signFB" method="get">
                <div><input type="submit" value="sign FB"></div>
              </form>
              <form action="Locator" method="post">
                <div><input type="submit" value="Google!"></div>
              </form>
            </body>
          </html>""")

class BaseHandler(webapp.RequestHandler):
    def get_user_from_cookie(cookies, app_id, app_secret):
        cookie = cookies.get("vk_app_" + app_id, "")
        if not cookie: return None
        args = dict((k, v[-1]) for k, v in cgi.parse_qs(cookie.strip('"')).items())
        payload = "".join(k + "=" + args[k] for k in sorted(args.keys())
                          if k != "sig")
        sig = hashlib.md5(payload + app_secret).hexdigest()
        expires = int(args["expires"])
        if sig == args.get("sig") and (expires == 0 or time.time() < expires):
            return args
        else:
            return None

    @property
    def current_user_vk(self):
        if not hasattr(self, "_current_user_vk"):
            self._current_user_vk = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies, VKONTAKTE_APP_ID, VKONTAKTE_APP_SECRET)
            if cookie:
                user = UserVK.get_by_key_name(cookie["mid"])
                if not user:
                    user = UserVK(key_name=str(cookie["mid"]),
                                id=str(cookie["mid"]),
                                name=cookie["mid"],
                                sid=cookie["sid"],
                                secret=cookie["secret"],
                                expire=int(cookie["secret"]))
                    user.put()
                elif user.sid != cookie["sid"]:
                    user.sid = cookie["sid"]
                    user.put()
                self._current_user_vk = user
        return self._current_user_vk

    @property
    def current_user_fb(self):
        if not hasattr(self, "_current_user_fb"):
            self._current_user_fb = None
            cookie = facebook.get_user_from_cookie(
                self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
            if cookie:
                user = UserFB.get_by_key_name(cookie["uid"])
                if not user:
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    user = UserFB(key_name=str(profile["id"]),
                                id=str(profile["id"]),
                                name=profile["name"],
                                profile_url=profile["link"],
                                access_token=cookie["access_token"])
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                self._current_user_fb = user
        return self._current_user_fb


class Locator(webapp.RequestHandler):
    def post(self):
        self.redirect('http://google.ru')


class authVK(BaseHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), "authVK.html")
        args = dict(current_user_vk=self.current_user_vk,
                    VKONTAKTE_APP_ID=VKONTAKTE_APP_ID)
        self.response.out.write(template.render(path, args))


class authFB(BaseHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__), "authFB.html")
        args = dict(current_user_fb=self.current_user_fb,
                    facebook_app_id=FACEBOOK_APP_ID)
        self.response.out.write(template.render(path, args))



application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/signVK', authVK),
                                      ('/Locator', Locator),
                                      ('/signFB', authFB)],
                                     debug=True)


def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()